﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
using System.IO;

namespace Yuyi.PluginForJS.Addin
{
    public class CodeService
    {
        private DTE _dte;
        private Document _doc;

        public CodeService(DTE dte,Document doc)
        {
            this._dte = dte;
            this._doc = doc;
        }
        public TextSelection Selection
        {
            get 
            {
                if (_doc == null)
                    return null;
                else
                {
                    TextDocument textDocument = (TextDocument)_doc.Object("TextDocument");
                    return textDocument.Selection;
                }
            }
        }

        public string LoadCode()
        {
            if (_doc == null) return string.Empty;
            if (_doc.FullName.EndsWith("js"))
            {
                using (StreamReader reader = new StreamReader(_doc.FullName))
                {
                    return reader.ReadToEnd();
                }
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                string searchScriptBegin = "<script";
                string searchScriptEnd = "</script>";

                Selection.StartOfDocument(false);
                TextRanges textRanges = null;
                while (Selection.FindPattern(searchScriptBegin, 0, ref textRanges))
                {
                    int startLine = Selection.TopLine + 1;
                    Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);
                    int startColumn = Selection.CurrentColumn;
                    if (Selection.FindPattern(searchScriptEnd, 0, ref textRanges))
                    {
                        Selection.MoveToLineAndOffset(startLine, startColumn, true);
                        for (int i = 1; i < Selection.TopLine; i++)
                            sb.Append("\t\n");

                        sb.Append(Selection.Text);
                    }
                }
                return sb.ToString();
            }
        }
    }
}
